package com.example.controller.pc;

import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.annotation.Log;
import com.example.common.result.Result;
import com.example.entity.dto.pc.*;
import com.example.entity.mysql.Resource;
import com.example.entity.mysql.Resourcegroup;
import com.example.entity.mysql.Workresource;
import com.example.entity.vo.pc.MouldListVo;
import com.example.entity.vo.pc.NeedMouldListVo;
import com.example.entity.yifei.*;
import com.example.enums.MOCStatusEnum;
import com.example.enums.MouldStatusEnum;
import com.example.exception.CustomException;
import com.example.mapper.*;
import com.example.mapper.pc.ResourceMapper;
import com.example.mapper.pc.WorkresourceMapper;
import com.example.service.MaconlineinfoService;
import com.example.service.pc.ResourceService;
import com.example.service.pc.ResourcegroupService;
import com.example.untils.BeanUtils;
import com.example.untils.StringUtils;
import com.example.untils.TimeUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@Api(tags = "模具管理")
@RequestMapping("/api/mould")
public class MouldController {

    @Autowired
    private MaconlineinfoService maconlineinfoService;
    @Autowired
    private MaconlineinfoMapper maconlineinfoMapper;
    @Autowired
    private MaconlineinfohistoryMapper maconlineinfohistoryMapper;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private MoctyMapper moctyMapper;
    @Autowired
    private ResourceMapper resourceMapper;
    @Autowired
    private WorkresourceMapper workresourceMapper;
    @Autowired
    private ResourcegroupService resourceGroupService;
    @Autowired
    private ResourceusehisMapper resourceusehisMapper;
    @Autowired
    private CmsmdMapper cmsmdMapper;

    @ApiOperation("模具列表")
    @PostMapping("mouldList")
    public Result<PageInfo<List<MouldListVo>>> resourceList(@RequestBody MouldListDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<MouldListVo> list = resourceMapper.mouldList(dto);
        for(MouldListVo vo : list) {  // 查询模具对应的机器是哪个，机器所生产的工单又是哪个
            // 去macOnlineInfo上找，对应的机器号
            Maconlineinfo maconlineinfo = maconlineinfoMapper.selectOne(new LambdaQueryWrapper<Maconlineinfo>().eq(Maconlineinfo::getResourceno, vo.getDeviceid()));
            if(maconlineinfo != null) {
                vo.setMacNo(maconlineinfo.getMacno());
                if(StringUtils.isEmpty(maconlineinfo.getMacno())) continue;
                Resource resource = resourceMapper.selectOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, maconlineinfo.getMacno()));
                if(resource == null) continue;
                // SELECT * FROM MOCTY WHERE UDF05 = 'AMM2AMM2024-011948-CT-SBD-19-004-D01'
                // SELECT * FROM MOCTY WHERE UDF02 = 'a4e6c9ab-8395-4be7-a494-88310d595f7c'
                if(StringUtils.isEmpty(resource.getMoctyudf05())) continue;
                Mocty one = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, resource.getMoctyudf05()));
                if(one == null) continue;
                if(StringUtils.isNotEmpty(one.getUdf02())) {
                    List<Mocty> moctyList = moctyMapper.selectList(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf02, one.getUdf02()));
                    StringBuffer sb = new StringBuffer();
                    for(Mocty x : moctyList) {
                        sb.append(x.getTy001()+"-"+x.getTy002()+",");
                    }
                    if(sb.length() > 0) sb.deleteCharAt(sb.length() - 1);
                    vo.setDoingWork(sb.toString());
                }else{
                    vo.setDoingWork(one.getTy001()+"-"+one.getTy002());
                }
            }
        }
        PageInfo<List<MouldListVo>> pageInfo = new PageInfo(list);
        return Result.success(pageInfo);
    }

    @ApiOperation("模具详情")
    @PostMapping("mouldDetailInfo")
    public Result<MouldListVo> mouldDetailInfo(@RequestBody MouldListDto dto) {
        MouldListVo res = resourceMapper.mouldDetailInfo(dto);
        return Result.success(res);
    }

    @ApiOperation("模具所有的状态")
    @PostMapping("mouldAllStatus")
    public Result<List<String>> mouldAllStatus() {
        return Result.success(MouldStatusEnum.getAllStatuses());
    }

    @ApiOperation("模具编辑时能修改的状态")
    @PostMapping("mouldCanUpdateStatus")
    public Result<List<String>> canUpdateStatus() {
        List<String> res = new ArrayList<>();
        res.add(MouldStatusEnum.XianZhi.getValue());
        res.add(MouldStatusEnum.YiZuoFei.getValue());
        res.add(MouldStatusEnum.YiBaoFei.getValue());
        res.add(MouldStatusEnum.YiShenHe.getValue());
        res.add(MouldStatusEnum.YiTingYong.getValue());
        return Result.success(res);
    }

    @ApiOperation("模具编辑")
    @PostMapping("editMould")
    @DSTransactional
    public Result editMould(@RequestBody EditMouldDto dto) {
        //模具编号和模具名称
        if(StringUtils.isEmpty(dto.getDeviceid()) || StringUtils.isEmpty(dto.getDevicename())) {
            return Result.error("模具编号和模具名称不能为空");
        }
        //资源ID
        if(dto.getResourceid() == null) {
            return Result.error("资源ID不能为空");
        }

        Resource originData = resourceService.getOne(new LambdaQueryWrapper<Resource>()
                .eq(Resource::getResourceid, dto.getResourceid()));
        if(originData == null) {
            return Result.error("原数据不存在");
        }
        if(MouldStatusEnum.ShiYongZhong.getValue().equals(originData.getStatus().trim())
        || MouldStatusEnum.YiLingYong.getValue().equals(originData.getStatus().trim())
        || MouldStatusEnum.DaiLingYong.getValue().equals(originData.getStatus().trim())
        || MouldStatusEnum.DaiGuiHuan.getValue().equals(originData.getStatus().trim())
        || MouldStatusEnum.GuiHuanDaiQueRen.getValue().equals(originData.getStatus().trim()))
        {
            return Result.error("模具状态为: 使用中, 已领用, 待领用, 待归还, 归还待确认时。不能修改状态。");
        }

        Resource resource = new Resource();
        BeanUtils.copyPropertiesIgnoreCase(dto, resource);

        // 有没有和其他的编号重复
        Resource one = resourceService.getOne(new LambdaQueryWrapper<Resource>()
                .eq(Resource::getDeviceid, resource.getDeviceid()));
        if(one != null && !one.getResourceid().equals(resource.getResourceid())) {
            return Result.error("模具编号已被使用");
        }
        //根据资源id查资源组id
        one = resourceService.getOne(new LambdaQueryWrapper<Resource>()
                .eq(Resource::getResourceid, resource.getResourceid()));
        //更新资源组
        Resourcegroup resourcegroup = new Resourcegroup();
        resourcegroup.setResourceGroupId(one.getResourceGroupIdIsF());
        resourcegroup.setResourceGroupNO(resource.getDeviceid());
        resourcegroup.setResourceGroupName(resource.getDevicename());
        resourceGroupService.updateById(resourcegroup);
        //更新资源
        boolean b = resourceService.updateById(resource);
        if(b) return Result.success("修改模具成功");
        else return Result.success("修改模具失败");
    }

    @ApiOperation("获取该机器上，正在上机的模具和工单需要的模具")
    @PostMapping("needMouldList")
    public Result<NeedMouldListVo> needMouldList(@RequestBody NeedMouldListDto dto) {
        if(StringUtils.isEmpty(dto.getMacNo()) || StringUtils.isEmpty(dto.getMoctyUuid())) {
            return Result.error("机器编号和排产UUID不能为空!");
        }
        NeedMouldListVo vo = new NeedMouldListVo();
        List<Maconlineinfo> maconlineinfoList = maconlineinfoMapper.selectList(new LambdaQueryWrapper<Maconlineinfo>()
                .eq(Maconlineinfo::getMacno, dto.getMacNo()));
        List<ComfirmResourceItemDto> nowMouldList = new ArrayList<>();
        for(Maconlineinfo t : maconlineinfoList) {
            ComfirmResourceItemDto y = new ComfirmResourceItemDto();
            y.setMouldId(t.getResourceId());
            y.setMouldNo(t.getResourceno());
            y.setMouldName(t.getResourcename());
            y.setMouldType(t.getResourcetype());
            nowMouldList.add(y);
        }
        vo.setNowMouldList(nowMouldList);

        List<ComfirmResourceItemDto> needMouldList = new ArrayList<>();
        Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, dto.getMoctyUuid()));
        String ty003 = mocty.getTy003();
        List<Workresource> workresourceList = workresourceMapper.selectList
                (new LambdaQueryWrapper<Workresource>().eq(Workresource::getProductLineId, ty003));
        for(Workresource t : workresourceList) {
            Resource resource = resourceMapper.selectOne(new LambdaQueryWrapper<Resource>().eq(Resource::getResourceGroupIdIsF, t.getResourceId()));
            if(resource.getResourceType().equals(1) || resource.getResourceType().equals(2)) continue;
            ComfirmResourceItemDto y = new ComfirmResourceItemDto();
            Resourcegroup resourcegroup = resourceGroupService.getOne(new LambdaQueryWrapper<Resourcegroup>().eq(Resourcegroup::getResourceGroupId, t.getResourceId()));
            y.setMouldId(t.getResourceId());
            y.setMouldNo(resourcegroup.getResourceGroupNO());
            y.setMouldName(resourcegroup.getResourceGroupName());
            y.setMouldType(resource.getResourceType());
            needMouldList.add(y);
        }
        vo.setNeedMouldList(needMouldList);
        return Result.success(vo);
    }

    @ApiOperation("上模具")
    @PostMapping("shangmuju")
    @DSTransactional
    @Log("上模具")
    public Result shangmuju(@RequestBody ShangmujuDto dto) {
        if(dto.getMouldType() == null) {
            return Result.error("资源类型不能为空!");
        }
        // 判断现在上面有没有模具。  模具的话才需要判断，工装的话是不用做判断的
        if(dto.getMouldType().equals(3)) {
            List<Maconlineinfo> maconlineinfoList = maconlineinfoMapper.selectList(new LambdaQueryWrapper<Maconlineinfo>()
                    .eq(Maconlineinfo::getMacno, dto.getMacNo())
                    .eq(Maconlineinfo::getResourcetype, dto.getMouldType()));
            if(maconlineinfoList != null && maconlineinfoList.size() > 0) {
                throw new CustomException("500", "当前机器上已有模具在使用");
            }
        }

        Maconlineinfo maconlineinfo = new Maconlineinfo();
        maconlineinfo.setMouldOnTime(TimeUtils.getFullNowTime());
        Resource macInfo = resourceMapper.selectOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMacNo()));
        if(macInfo == null) {
            throw new CustomException("500", "机器编号不存在");
        }
        if(StringUtils.isNotEmpty(macInfo.getMoctyudf05())) {
            Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, macInfo.getMoctyudf05()));
            if(mocty != null) {
                if(MOCStatusEnum.DaiMuJuQueRen.getValue().equals(mocty.getUdf01().trim())) {

                }else{
                    throw new CustomException("500", "工单在[待模具确认]时, 才可以上模。");
                }
            }
        }

        maconlineinfo.setMacid(macInfo.getResourceGroupIdIsF());
        maconlineinfo.setMacno(macInfo.getDeviceid());
        maconlineinfo.setMacname(macInfo.getDevicename());
        maconlineinfo.setWorkCenterId(macInfo.getWorkCenter());
        if(StringUtils.isNotEmpty(macInfo.getWorkCenter())) maconlineinfo.setWorkCenterName(cmsmdMapper.getByMD001(macInfo.getWorkCenter()).getMd002());
        Resource mouldInfo = resourceMapper.selectOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMouldNo()));
//        if(!MouldStatusEnum.XianZhi.getValue().equals(mouldInfo.getStatus().trim())
//                && !MouldStatusEnum.YiShenHe.getValue().equals(mouldInfo.getStatus().trim())) {
        if(!MouldStatusEnum.YiLingYong.getValue().equals(mouldInfo.getStatus().trim()) && !MouldStatusEnum.DaiGuiHuan.getValue().equals(mouldInfo.getStatus().trim())) {
            throw new CustomException("500", "当前模具不在[已领用] 或者 [待归还] 状态");
        }
//        if(!MouldStatusEnum.YiLingYong.getValue().equals(mouldInfo.getStatus().trim())) {
//            throw new CustomException("500", "当前模具不在已领用的状态");
//        }
        maconlineinfo.setResourcetype(dto.getMouldType());
        maconlineinfo.setResourceId(mouldInfo.getResourceGroupIdIsF());
        maconlineinfo.setResourceno(mouldInfo.getDeviceid());
        maconlineinfo.setResourcename(mouldInfo.getDevicename());
        maconlineinfoMapper.insert(maconlineinfo);
        // 没有的话，可以上。判断模具的状态，是不是已领取出库，  // 是的话，修改为 使用中
        mouldInfo.setStatus(MouldStatusEnum.ShiYongZhong.getValue());
        mouldInfo.setMacOnTime(maconlineinfo.getMouldOnTime());  // 改一下上模时间
        mouldInfo.setMaintainTime(maconlineinfo.getMouldOnTime());  //
        resourceMapper.update(mouldInfo, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMouldNo()));

        return Result.success();
    }

    @ApiOperation("下模具")
    @PostMapping("xiamuju")
    @DSTransactional
    @Log("下模具")
    public Result xiamuju(@RequestBody XiamujuDto dto) {

        Resource resource = resourceMapper.selectOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMouldNo()));
        if(resource == null) {
            throw new CustomException("500", "该模具不存在");
        }
        // 直接将状态修改掉
        Maconlineinfo maconlineinfo = maconlineinfoMapper.selectOne(new LambdaQueryWrapper<Maconlineinfo>()
                .eq(Maconlineinfo::getMacno, dto.getMacNo())
                .eq(Maconlineinfo::getResourceno, dto.getMouldNo())
                .eq(Maconlineinfo::getResourcetype, dto.getMouldType()));
        if(maconlineinfo == null) {
            throw new CustomException("500", "该模具不在机器上");
        }
        // 判断机器和机器上工单的状态。
        Resource macInfo = resourceMapper.selectOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMacNo()));
        if(macInfo == null) {
            throw new CustomException("500", "机器编号不存在");
        }
        if(StringUtils.isNotEmpty(macInfo.getMoctyudf05())) {
            Mocty mocty = moctyMapper.selectOne(new LambdaQueryWrapper<Mocty>().eq(Mocty::getUdf05, macInfo.getMoctyudf05()));
            if(mocty != null) {
                if(MOCStatusEnum.DaiMuJuQueRen.getValue().equals(mocty.getUdf01().trim())) {

                }else{
                    throw new CustomException("500", "工单在[待模具确认]时, 才可以下模。");
                }
            }
        }

        maconlineinfo.setMouldOutTime(TimeUtils.getFullNowTime());
        // 将这条转移到历史表中。 然后删掉
        Maconlineinfohistory history = new Maconlineinfohistory();
        BeanUtils.copyPropertiesIgnoreCase(maconlineinfo, history);
        maconlineinfohistoryMapper.insert(history);
        maconlineinfoMapper.delete(new LambdaQueryWrapper<Maconlineinfo>()
                .eq(Maconlineinfo::getMacno, dto.getMacNo())
                .eq(Maconlineinfo::getResourceno, dto.getMouldNo())
                .eq(Maconlineinfo::getResourcetype, dto.getMouldType()));

//        resource.setStatus(MouldStatusEnum.DaiGuiHuan.getValue());
        resource.setStatus(MouldStatusEnum.DaiGuiHuan.getValue());
        resource.setMacOnTime("");  // 改一下上模时间
        resource.setMaintainTime("");
        resourceMapper.update(resource, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMouldNo()));

        return Result.success();
    }

    @ApiOperation("批量下模具")
    @PostMapping("xiamujuBatch")
    @DSTransactional
    @Log("批量下模具")
    public Result xiamujuBatch(@RequestBody List<XiamujuDto> list) {

        for(XiamujuDto dto : list) {
            Resource resource = resourceMapper.selectOne(new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMouldNo()));
            if(resource == null) {
                throw new CustomException("500", "模具" + dto.getMouldNo() + "不存在");
            }
            // 直接将状态修改掉
            Maconlineinfo maconlineinfo = maconlineinfoMapper.selectOne(new LambdaQueryWrapper<Maconlineinfo>()
                    .eq(Maconlineinfo::getMacno, dto.getMacNo())
                    .eq(Maconlineinfo::getResourceno, dto.getMouldNo())
                    .eq(Maconlineinfo::getResourcetype, dto.getMouldType()));
            if(maconlineinfo == null) {
                throw new CustomException("500", "模具" + dto.getMouldNo() + "不在机器上");
            }
            maconlineinfo.setMouldOutTime(TimeUtils.getFullNowTime());
            // 将这条转移到历史表中。 然后删掉
            Maconlineinfohistory history = new Maconlineinfohistory();
            BeanUtils.copyPropertiesIgnoreCase(maconlineinfo, history);
            maconlineinfohistoryMapper.insert(history);
            maconlineinfoMapper.delete(new LambdaQueryWrapper<Maconlineinfo>()
                    .eq(Maconlineinfo::getMacno, dto.getMacNo())
                    .eq(Maconlineinfo::getResourceno, dto.getMouldNo())
                    .eq(Maconlineinfo::getResourcetype, dto.getMouldType()));
//          resource.setStatus(MouldStatusEnum.DaiGuiHuan.getValue());
            resource.setStatus(MouldStatusEnum.DaiGuiHuan.getValue());
            resource.setMacOnTime("");  // 改一下上模时间
            resource.setMaintainTime("");
            resourceMapper.update(resource, new LambdaQueryWrapper<Resource>().eq(Resource::getDeviceid, dto.getMouldNo()));
        }

        return Result.success();
    }

    @ApiOperation("模具/工装历史使用情况")
    @PostMapping("mouldUseStatus")
    public Result< PageInfo<List<Macstatuslog>>> mouldUseStatus(@RequestBody MouldUseStatusDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<Resourceusehis> resourceusehis = resourceusehisMapper.selectList(new LambdaQueryWrapper<Resourceusehis>()
                .eq(Resourceusehis::getResourceno, dto.getResourceNo()).orderByDesc(Resourceusehis::getCreateTime));
        PageInfo<List<Macstatuslog>> pageInfo = new PageInfo(resourceusehis);
        return Result.success(pageInfo);
    }

    @ApiOperation("模具新增")
    @PostMapping("addMould")
    @DSTransactional
    public Result addMould(@RequestBody AddMouldDto dto) {
        //模具编号和模具名称
        if(StringUtils.isEmpty(dto.getDeviceid()) || StringUtils.isEmpty(dto.getDevicename())) {
            return Result.error("模具编号和模具名称不能为空");
        }
        if(dto.getResourceGroupId() == null) {
            return Result.error("资源组ID不能为空,需要指定一个上级");
        }
        if(dto.getCavityNumber() == null || dto.getSafeDesignLife() == null || dto.getDesignLife() == null) {
            return Result.error("[模穴数]/[安全模次数]/[预估总生产模次数]不能为空。");
        }
        if(StringUtils.isEmpty(dto.getStatus())) {
            return Result.error("模具状态不能为空。");
        }
        //资源ID必须为空
//        dto.setResourceid(null);

        Resource resource = new Resource();
        BeanUtils.copyPropertiesIgnoreCase(dto, resource);
        resource.setResourceType(3);  // 指定为模具。
        // 有没有和其他的编号重复
        Resource one = resourceService.getOne(new LambdaQueryWrapper<Resource>()
                .eq(Resource::getDeviceid, resource.getDeviceid()));
        if(one != null) return Result.error("模具编号已被使用");

        //更新资源组
        Resourcegroup resourcegroup = new Resourcegroup();
        resourcegroup.setResourceGroupNO(resource.getDeviceid());
        resourcegroup.setResourceGroupName(resource.getDevicename());
        resourcegroup.setType("F");
        resourcegroup.setResourceGroupParentId(resource.getResourceGroupId());
        resourceGroupService.save(resourcegroup);
        resource.setResourceGroupIdIsF(resourcegroup.getResourceGroupId());
        boolean b = resourceService.save(resource);
        if(b) return Result.success("新增模具成功");
        else return Result.success("新增模具失败");
    }
}
